package com.yigoushangcheng.oauth.controller;

import com.yigoushangcheng.oauth.service.AuthService;
import com.yigoushangcheng.oauth.util.AuthToken;
import com.yigoushangcheng.oauth.util.CookieUtil;
import com.fcgzs.entity.Result;
import com.fcgzs.entity.StatusCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: ljj
 * @Description:
 */
@RestController
@RequestMapping("/user")
public class AuthController {

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;


    @Autowired
    private AuthService authService;


    @PostMapping("/login")
    public Result login(String username, String password, HttpServletResponse response){

        //1.判断用户名或密码不能为空
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("密码不能为空");
        }

        //2.调用方法取得令牌
        AuthToken authToken = authService.login(clientId, clientSecret, username, password);
        String token = authToken.getAccessToken();   //令牌信息
        //3.将令牌放入cookie中
        CookieUtil.addCookie(response,cookieDomain,"/","Authorization",token,cookieMaxAge,false);
        return new Result(true, StatusCode.OK,"登录成功");
    }
}
